import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Effects

Item {
    id: root
    width: 800
    height: 1000

    Theme {
        id: theme
    }

    property real value: 482.00
    property real minValue: 0
    property real maxValue: 600
    property real stepSize: 1
    property string icon: "SV"
    property string unit: "rpm"
    property string title: "当前转速"
    property string setTitle: "设定转速:"
    property color startColor: "#00c2c7"   // 内环颜色
    property color endColor: "#0066ff"     // 外环颜色
    property real arcWidth: 30
    property real progress: (value - minValue) / (maxValue - minValue)
    // 环形参数（不使用 Canvas）
    property real startAngleDeg: -120
    property real spanAngleDeg: 240

    // 开关属性
    property bool incDecEnabled: true
    property bool sliderEnabled: false
    property bool sliderIncDecEnabled: true
    property bool ticksEnabled: true

    signal valueModified(real newValue)

    Rectangle {
        id: knobBackground
        anchors.top: parent.top
        anchors.horizontalCenter: parent.horizontalCenter
        width: 760
        height: width
        radius: width / 2
        color: "transparent"
        // color: "#88888888"

        // 外圈刻度层
        Item {
            z: 0
            id: ticksLayer
            anchors.fill: parent
            visible: ticksEnabled
            property int tickCount: 26
            property int majorStep: 5
            property int tickTopMargin: 8       // 刻度离外圈的距离
            property int outerPadding: 30        // 缩小刻度层半径
            property color minorColor: '#87bbeb'
            property color majorColor: "#178FCD"
            anchors.margins: outerPadding

            Repeater {
                model: ticksLayer.tickCount
                delegate: Item {
                    width: knobBackground.width
                    height: knobBackground.height
                    anchors.centerIn: parent
                    transformOrigin: Item.Center
                    property bool major: index % ticksLayer.majorStep === 0
                    property real angleDeg: root.startAngleDeg + index * (root.spanAngleDeg / (ticksLayer.tickCount - 1))
                    rotation: angleDeg

                    // 刻度线
                    Rectangle {
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.top: parent.top
                        anchors.topMargin: ticksLayer.tickTopMargin
                        width: major ? 2 : 1
                        height: major ? 24 : 18
                        radius: width / 2
                        color: major ? ticksLayer.majorColor : ticksLayer.minorColor
                    }

                    // 主刻度数字
                    Text {
                        visible: major
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.top: parent.top
                        anchors.topMargin: -35
                        text: Math.round(root.minValue + (index / (ticksLayer.tickCount - 1)) * (root.maxValue - root.minValue))
                        font.pixelSize: 24
                        color: ticksLayer.majorColor
                        rotation: -angleDeg     // 保持文字正立
                    }
                }
            }
        }

        // 数值指示器
        Item {
            z: 2
            id: valueIndicator
            anchors.fill: parent
            visible: true
            
            property real currentAngle: root.startAngleDeg + (root.value - root.minValue) / (root.maxValue - root.minValue) * root.spanAngleDeg
            property real indicatorRadius: (knobBackground.width / 2) - ticksLayer.outerPadding - ticksLayer.tickTopMargin - 52
            
            Image {
                id: indicatorPoint
                source: "qrc:/assets/jbpoint.png"
                width: 30
                height: 30
                anchors.centerIn: parent
                // 根据当前数值计算位置
                transform: [
                    Translate {
                        x: Math.sin(valueIndicator.currentAngle * Math.PI / 180) * valueIndicator.indicatorRadius
                        y: -Math.cos(valueIndicator.currentAngle * Math.PI / 180) * valueIndicator.indicatorRadius
                    }
                ]
            }
        }

        // 文本
        Rectangle {
            z: 2
            id: centerCircle
            anchors.centerIn: parent
            width: parent.width
            height: width
            color: "transparent"

        
            Column {
                anchors.centerIn: parent
                anchors.verticalCenterOffset: -14
                anchors.horizontalCenterOffset: 3
                width: 300
                spacing: 16
                Text { 
                    text: icon
                    color: "#6D7278"
                    font.pixelSize: 36
                    anchors.horizontalCenter: parent.horizontalCenter
                }
                
                // 显示/输入区域
                Item {
                    width: 200
                    height: 100
                    anchors.horizontalCenter: parent.horizontalCenter
                    
                    property bool isEditing: false
                    
                    // 显示
                    Text { 
                        id: valueDisplay
                        text: value.toFixed(0)
                        font.pixelSize: 80
                        font.bold: true
                        color: "#333"
                        anchors.centerIn: parent
                        visible: !parent.isEditing
                        
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                parent.parent.isEditing = true
                                centerValueInput.text = value.toFixed(0)
                                centerValueInput.forceActiveFocus()
                                centerValueInput.selectAll()
                            }
                        }
                    }
                    
                    // 编辑
                    Rectangle {
                        id: inputBackground
                        anchors.centerIn: parent
                        width: 180
                        height: 80
                        visible: parent.isEditing
                        color: "transparent"
                        
                        Image {
                            anchors.fill: parent
                            source: "qrc:/assets/jbinput.png"
                            fillMode: Image.Stretch
                        }
                        
                        TextInput {
                            id: centerValueInput
                            anchors.centerIn: parent
                            width: parent.width - 20
                            height: parent.height - 10
                            font.pixelSize: 60
                            font.bold: true
                            color: "#178FCD"
                            horizontalAlignment: TextInput.AlignHCenter
                            verticalAlignment: TextInput.AlignVCenter
                            validator: DoubleValidator {
                                bottom: root.minValue
                                top: root.maxValue
                                decimals: 0
                            }
                            
                            onAccepted: {
                                var newValue = parseFloat(text)
                                if (!isNaN(newValue)) {
                                    root.value = Math.max(root.minValue, Math.min(root.maxValue, newValue))
                                    root.valueModified(root.value)
                                }
                                parent.parent.isEditing = false
                            }
                            
                            Keys.onEscapePressed: {
                                parent.parent.isEditing = false
                            }
                            
                            onActiveFocusChanged: {
                                if (!activeFocus) {
                                    parent.parent.isEditing = false
                                }
                            }
                        }
                    }
                }
                
                Text { 
                    text: unit
                    font.pixelSize: 26
                    color: "#666"
                    anchors.horizontalCenter: parent.horizontalCenter
                }
            }
        }
    }

    // 控制区域
    Rectangle {
        id: controlArea
        anchors.top: knobBackground.bottom
        anchors.topMargin: 40
        anchors.horizontalCenter: parent.horizontalCenter
        width: knobBackground.width
        height: 120
        radius: 60
        color: "#ffffff"
        visible: incDecEnabled


        Rectangle {
            id: controlAreaContent
            anchors.fill: parent
            radius: 60
            color: "#ffffff"
        }

        RowLayout {
            anchors.fill: parent
            anchors.margins: 10
            spacing: 8

            EButton {
                id: minusButton
                text: "-"
                Layout.preferredWidth: 100
                Layout.preferredHeight: 100
                buttonColor: "#DCE7F2"
                textColor: "#333"
                radius: 50
                iconCharacter: ""
                visible: incDecEnabled
                onClicked: {
                    var newValue = Math.max(root.minValue, root.value - root.stepSize);
                    if (newValue !== root.value) {
                        root.value = newValue;
                        root.valueModified(root.value);
                    }
                }
            }

            ColumnLayout {
                Layout.fillWidth: true
                Layout.fillHeight: true
                spacing: 0

                Text {
                    id: setTitleText
                    text: root.setTitle
                    font.pixelSize: 28
                    color: "#666666"
                    Layout.alignment: Qt.AlignHCenter
                }

                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 60
                    Layout.alignment: Qt.AlignHCenter
                    color: "transparent"

                    TextInput {
                        id: valueInput
                        anchors.fill: parent
                        horizontalAlignment: TextInput.AlignHCenter
                        verticalAlignment: TextInput.AlignVCenter
                        text: root.value.toFixed(0)
                        font.pixelSize: 36
                        color: "#333333"
                        selectByMouse: true
                        validator: IntValidator {
                            bottom: root.minValue
                            top: root.maxValue
                        }

                        onEditingFinished: {
                            var newValue = parseInt(text);
                            if (!isNaN(newValue) && newValue >= root.minValue && newValue <= root.maxValue) {
                                root.value = newValue;
                                root.valueModified(root.value);
                            } else {
                                text = root.value.toFixed(0);
                            }
                        }
                    }
                }
            }

            EButton {
                id: plusButton
                text: "+"
                Layout.preferredWidth: 100
                Layout.preferredHeight: 100
                buttonColor: "#DCE7F2"
                textColor: "#333"
                radius: 50
                iconCharacter: ""
                visible: incDecEnabled
                onClicked: {
                    var newValue = Math.min(root.maxValue, root.value + root.stepSize);
                    if (newValue !== root.value) {
                        root.value = newValue;
                        root.valueModified(root.value);
                    }
                }
            }
        }
    }

    // 水平滑块进度条
    Rectangle {
        id: sliderContainer
        anchors.top: knobBackground.bottom
        anchors.topMargin: 20
        anchors.horizontalCenter: parent.horizontalCenter
        width: Math.min(parent.width * 0.92, 720)
        height: 80
        radius: 40
        color: "transparent"
        visible: sliderEnabled

        MultiEffect {
            source: sliderContent
            anchors.fill: sliderContent
            shadowEnabled: true
            shadowColor: theme.shadowColor
            shadowBlur: theme.shadowBlur
            shadowVerticalOffset: theme.shadowYOffset
            shadowHorizontalOffset: theme.shadowXOffset
        }

        Rectangle {
            id: sliderContent
            anchors.fill: parent
            radius: 60
            color: "transparent"
        }

        // 加减
        Text {
            id: sliderMinusText
            text: "-"
            color: "#333"
            font.pixelSize: 36
            anchors.left: parent.left
            anchors.verticalCenter: parent.verticalCenter
            visible: sliderIncDecEnabled
            // 点击区域
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    var newValue = Math.max(root.minValue, root.value - root.stepSize);
                    if (newValue !== root.value) {
                        root.value = newValue;
                        root.valueModified(root.value);
                    }
                }
            }
        }

        Text {
            id: sliderPlusText
            text: "+"
            color: "#333"
            font.pixelSize: 36
            anchors.right: parent.right
            anchors.verticalCenter: parent.verticalCenter
            visible: sliderIncDecEnabled
            // 点击区域
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    var newValue = Math.min(root.maxValue, root.value + root.stepSize);
                    if (newValue !== root.value) {
                        root.value = newValue;
                        root.valueModified(root.value);
                    }
                }
            }
        }

        Rectangle {
            id: sliderTrack
            anchors.verticalCenter: parent.verticalCenter
            anchors.left: sliderIncDecEnabled ? sliderMinusText.right : parent.left
            anchors.right: sliderIncDecEnabled ? sliderPlusText.left : parent.right
            anchors.leftMargin: sliderIncDecEnabled ? 12 : (parent.width * 0.05)
            anchors.rightMargin: sliderIncDecEnabled ? 12 : (parent.width * 0.05)
            height: 20
            radius: height / 2
            color: "#f0f0f0"
        }

        Rectangle {
            id: sliderFill
            anchors.left: sliderTrack.left
            anchors.verticalCenter: sliderTrack.verticalCenter
            width: sliderTrack.width * root.progress
            height: sliderTrack.height
            radius: height / 2
            gradient: Gradient {
                orientation: Gradient.Horizontal
                GradientStop { position: 0.0; color: root.startColor }
                GradientStop { position: 1.0; color: root.endColor }
            }
        }

        Rectangle {
            id: sliderThumb
            x: sliderTrack.x + (sliderTrack.width * root.progress) - (width / 2)
            y: sliderTrack.y + (sliderTrack.height - height) / 2
            width: 40
            height: 40
            radius: width / 2
            color: "#ffffff"
            MultiEffect {
                source: sliderThumb
                anchors.fill: sliderThumb
                shadowEnabled: true
                shadowColor: theme.shadowColor
                shadowBlur: theme.shadowBlur
                shadowVerticalOffset: theme.shadowYOffset
                shadowHorizontalOffset: theme.shadowXOffset
            }
            MouseArea {
                anchors.fill: parent
                drag.target: sliderThumb
                drag.axis: Drag.XAxis
                drag.minimumX: sliderTrack.x - (sliderThumb.width / 2)
                drag.maximumX: sliderTrack.x + sliderTrack.width - (sliderThumb.width / 2)
                onPositionChanged: {
                    var normalizedPos = Math.max(0, Math.min(1, (sliderThumb.x + sliderThumb.width / 2 - sliderTrack.x) / sliderTrack.width));
                    var newValue = root.minValue + normalizedPos * (root.maxValue - root.minValue);
                    newValue = Math.round(newValue / root.stepSize) * root.stepSize;
                    if (newValue !== root.value) {
                        root.value = newValue;
                        root.valueModified(root.value);
                    }
                }
            }
        }
    }

    // 监听 value 变化（无需 Canvas 重绘）
    onValueChanged: {
        // Shape 会自动根据绑定更新
    }
}
